import { Toast } from 'vant'
import { computed, inject, getCurrentInstance, reactive } from 'vue'
import {useRouter} from 'vue-router'
import { UserApi } from '@@/api/api.js'
import {useMeInfo} from '../../components/useMeInfo.js'

function useFeedback(){
    const {props,proxy} = getCurrentInstance()
    const router = useRouter()
    const {getFeedbackInfo} = useMeInfo()
    const state = reactive({
        feedbackInput:'',
        fsize:window.fsize,
    })
    const vueState = inject('vueState')
    const feedbackItem = computed(()=>{
        const item = vueState.pageInfo.feedbackInfo.list.find((item)=>{
            return item.id === JSON.parse(props.item).id
        })
        return item
        // return JSON.parse(props.item)
    })
    const feedbackList = computed(()=>{
        return vueState.pageInfo.feedbackInfo.list
    })
    const feedbackGroup = async()=> {
        if(!state.feedbackInput){
            Toast(proxy.$t('Please complete'))
            return
        }
        if(vueState.pageStatus.feedback){
            Toast(proxy.$t('Too fast. Please try again later'))
            return
        }
        Toast.loading({duration:0,message:`${proxy.$t('Loading')}...`})
        UserApi.FeedBack({
            feedBack:state.feedbackInput,
            contactInfo:'',
            groupId:feedbackItem.value.id
        }).then(()=>{
            getFeedbackInfo()
            Toast.success(proxy.$t('Success'))
            state.feedbackInput = ''
        }).catch((e)=>{
            console.log(e);
            setTimeout(()=>{
                Toast.clear()
            },3000)
        })
        vueState.pageStatus.setFeedback()
    }
    const showDetail = (item)=> {
        router.push({name:'feedbackDetail',params: { item: JSON.stringify(item) }})
    }
    const setReaded = (item)=>{
        try{
            UserApi.SetFeedbackReaded({readIds:[item.id]})
            vueState.pageInfo.feedbackInfo.list.forEach(el => {
                if(el.id === item.id){
                    el.readed = true
                    throw Error()
                }
            });
        }catch(e){
            // console.log(e);
        }
    }
    return {
        state,
        feedbackList,
        showDetail,
        feedbackItem,
        feedbackGroup,
        setReaded,
    } 
}
export {useFeedback}